const app = getApp();
const utils = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMore: 1,
    cardList: [],
    loadingMoreHidden: true,
    showCompany: false,
    showAi: false,
    windowHeight: '',
    newlists: [],
    keyword: "",
    classList: [],
    storeiid: 0,
    latitude: 0,
    longitude: 0,
    tagindex: 1, //1商家列表2消费卡3优惠券4管理我的
    top: 300,
    showDialog: false,
    projectname: '',
    qrCode: '',
    checkResult: {},
    couponList: [],
    carditems: []
  },
  tapClassSelect: function (e) {
    let cid = e.currentTarget.dataset.cid;
    let tagindex = this.data.tagindex;
    this.setData({
      storeiid: cid,
      CurrentPage: 1
    })
    if (tagindex == 1) {
      this.getAiCardList();
    }
    if (tagindex == 2) {
      this.getCardItems();
    }
    if (tagindex == 3) {
      this.getAllCoupon();
    }
  },
  changeTag: function (e) {
    let tagindex = e.currentTarget.dataset.tagindex;
    this.setData({
      tagindex: tagindex,
      CurrentPage: 1,
      loadingMore: 1
    })
    if (tagindex == 2) {
      this.getCardItems();
    } else if (tagindex == 3) {
      this.getAllCoupon();
    } else if (tagindex == 4) {
      app.globalData.diningSid = 0;
      var staffid = wx.getStorageSync("staffid");
      wx.redirectTo({
        url: '/pages/index/index?id=' + staffid,
      })
    } else {
      this.getAiCardList();
    }
  },

  // 获取店铺行业
  getIndustryList: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/store/GetIndustryList?storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            classList: res.data.Data
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      var res = wx.getSystemInfoSync();
      //每一个字母所占的高度
      this.apHeight = (res.windowHeight - 100) / 28;
      this.setData({
        windowHeight: res.windowHeight
      })
    } catch (e) {

    }
    this.getIndustryList();
  },

  handleInput: function (e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  handleBlur: function (e) {
    this.data.CurrentPage = 1;
    this.setData({
      keyword: e.detail.value
    })
  },
  handleConfirm: function (e) {
    this.data.CurrentPage = 1;
    this.setData({
      keyword: e.detail.value
    })
    let tagindex = this.data.tagindex;
    if (tagindex == 1) {
      this.getAiCardList();
    }
    if (tagindex == 2) {
      this.getCardItems();
    }
    if (tagindex == 3) {
      this.getAllCoupon();
    }
  },
  handleSearchWord: function () {
    let tagindex = this.data.tagindex;
    if (tagindex == 1) {
      this.getAiCardList();
    }
    if (tagindex == 2) {
      this.getCardItems();
    }
    if (tagindex == 3) {
      this.getAllCoupon();
    }
  },

  // 获取名片列表
  getAiCardList: function () {
    var that = this;
    let CurrentPage = that.data.CurrentPage;
    let pageSize = 10;
    wx.showLoading({
      title: '搜索中',
    })
    wx.request({
      url: app.globalData.host + '/api/BusinessCard/GetAiCardListByJJK?uid=' + app.globalData.userInfo.Uid + '&keyword=' + that.data.keyword + '&industryId=' + that.data.storeiid + '&latitude=' + that.data.latitude + '&longitude=' + that.data.longitude + '&page=' + CurrentPage + '&pageSize=' + pageSize,
      success: function (res) {
        wx.hideLoading();
        that.setData({
          loadingMoreHidden: false
        })
        if (res.data.Code == 0 && res.data.Data) {
          let cardList = res.data.Data.staff;
          let city = res.data.Data.city;
          if (CurrentPage != 1) {
            var preGoods = that.data.cardList;
            cardList = preGoods.concat(cardList);
          }
          for (let i = 0; i < cardList.length; i++) {
            let regionid = cardList[i].Regionid;
            for (let j = 0; j < city.length; j++) {
              let index = city[j].lastIndexOf("_");
              let str = city[j].substring(0, index);
              let str2 = city[j].substring(index + 1, city[j].length);
              if (str == regionid) {
                cardList[i].Address = str2 + cardList[i].Address;
                cardList[i].Distance = parseFloat(cardList[i].Distance).toFixed(2);
                cardList[i].Distances = parseFloat(cardList[i].Distance / 1000).toFixed(2);
              }
            }
            cardList[i].Avater = utils.formatAvater(cardList[i].Avater, 'https://static.711688.net.cn/upload/card/source/');
          }
          that.setData({
            cardList: cardList,
            loadingMore: res.data.Data.PageModel.TotalPages
          })
        }
      },
    })
  },

  tocardDetails: function (e) {
    let cardId = e.currentTarget.dataset.id;
    let lastCard = wx.getStorageSync('cardId');
    if (lastCard != cardId) {
      app.globalData.diningSid = 0;
    }
    wx.reLaunch({
      url: '/pages/home/index?id=' + cardId,
    })
  },

  //判断是否创建名片,显示‘管理我的’
  getStaffIdByUid: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              showAi: true
            })
            wx.setStorageSync("staffid", res.data.Data.Id)
          } else {
            that.setData({
              showAi: false
            });
            wx.removeStorageSync("staffid")
          }
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      that.getStaffIdByUid();
      that.getLocation();
    } else {
      setTimeout(function () {
        that.onShow();
      }, 1000)
    }
  },

  // 获取地理位置  
  getLocation: function () {
    let that = this;
    utils.getLocation((location)=>{
      that.data.latitude = location.lat;
      that.data.longitude = location.lng;
      that.getAiCardList();
    },app);   
  },

  // 获取优惠券
  getAllCoupon: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCouponListByDistance?uid=' + app.globalData.userInfo.Uid + '&longitude=' + that.data.longitude + '&latitude=' + that.data.latitude + '&page=' + that.data.CurrentPage + '&keyword=' + that.data.keyword + '&industryId=' + that.data.storeiid,
      success: function (res) {
        let couponList = res.data.Data.List;
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.couponList;
          couponList = preGoods.concat(couponList);
        }
        if (couponList.length > 0) {
          for (let i = 0; i < couponList.length; i++) {
            couponList[i].useendtime = couponList[i].useendtime.substr(0, 10);
            couponList[i].Logo = utils.formatAvater(couponList[i].Logo, 'https://static.711688.net.cn/upload/card/source/');
            if (couponList[i].Distance >= 1000) {
              couponList[i].Distances = parseFloat(couponList[i].Distance / 1000).toFixed(2);
            }
            var detailpics = couponList[i].DetailPics;
            couponList[i].showDetailPics = '';
            var list = [];
            if (detailpics != '') {
              var newDetailPics = detailpics.split(",");
              for (let k = 0; k < newDetailPics.length; k++) {
                list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
              }
              couponList[i].showDetailPics = list[0];
            }
          }
        }
        that.setData({
          couponList: couponList,
          loadingMore: res.data.Data.PageModel.TotalPages
        })
      }
    })
  },
  getCardItems: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/getcarditemlistbydistance?uid=' + app.globalData.userInfo.Uid + '&longitude=' + that.data.longitude + '&latitude=' + that.data.latitude + '&page=' + that.data.CurrentPage + '&keyword=' + that.data.keyword + '&industryId=' + that.data.storeiid,
      success: function (res) {
        let carditems = res.data.Data.List;
        if (that.data.CurrentPage != 1) {
          var preGoods = that.data.carditems;
          carditems = preGoods.concat(carditems);
        }
        if (carditems.length > 0) {
          for (let i = 0; i < carditems.length; i++) {
            carditems[i].ExpireTime = carditems[i].ExpireTime.substr(0, 10);
            carditems[i].Logo = utils.formatAvater(carditems[i].Logo, 'https://static.711688.net.cn/upload/card/source/');
            if (carditems[i].Distance >= 1000) {
              carditems[i].Distances = parseFloat(carditems[i].Distance / 1000).toFixed(2);
            }
            var detailpics = carditems[i].DetailPics;
            carditems[i].showDetailPics = '';
            var list = [];
            if (detailpics != '') {
              var newDetailPics = detailpics.split(",");
              for (let k = 0; k < newDetailPics.length; k++) {
                list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
              }
              carditems[i].showDetailPics = list[0];
            }
          }
        }
        that.setData({
          carditems: carditems,
          loadingMore: res.data.Data.PageModel.TotalPages
        })
      }
    })
  },
  // 优惠券二维码
  toQrCode: function (e) {
    let orderamountlower = e.currentTarget.dataset.orderamountlower;
    let name = e.currentTarget.dataset.name;
    let money = e.currentTarget.dataset.money;
    let couponid = e.currentTarget.dataset.couponid;
    let extcode1 = e.currentTarget.dataset.extcode1;
    let extcode2 = e.currentTarget.dataset.extcode2;
    let wxcoupontypeid = e.currentTarget.dataset.wxcoupontypeid;
    if (wxcoupontypeid != 0) {
      wx.showModal({
        title: '提示',
        content: '请打开微信扫一扫，扫商家收款码，支付时会自动核销代金券！',
        showCancel: false
      })
    } else {
      wx.navigateTo({
        url: '/merchant/merchants/qrCode/index?money=' + money + "&orderamountlower=" + orderamountlower + "&couponid=" + couponid + "&name=" + name + "&extcode1=" + extcode1 + "&extcode2=" + extcode2,
      })
    }

  },
  // 优惠券详情
  toCouponDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let couponid = e.currentTarget.dataset.couponid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&couponid=' + couponid,
    })
  },
  // 消费卡详情
  toCardItemDetail: function (e) {
    let type = e.currentTarget.dataset.type;
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=' + type + '&cid=' + cid,
    })
  },

  // 关闭二维码弹窗
  closeQrcode: function () {
    this.setData({
      showDialog: false,
      qrCode: ''
    })
    clearInterval(this.data.timer);
  },

  // 显示二维码
  showQrcode: function (e) {
    let cid = e.currentTarget.dataset.cid;
    let cardType = e.currentTarget.dataset.cardtype;
    let projectname = e.currentTarget.dataset.name;
    this.getQrcode(cid, cardType);
    this.setData({
      showDialog: !this.data.showDialog,
      projectname: projectname,
      checkResult: {}
    })
  },

  // 获取消费卡二维码
  getQrcode: function (cid, cardType) {
    var that = this;
    let cardId = wx.getStorageSync('cardId');
    let activetype = 2; //1充值，2核销
    if (cardType == 3) {
      activetype = 1;
    }
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: "merchant/share/sendOrcheckProject/index?t=6&p=" + cid + '#' + cardType + '#' + app.globalData.userInfo.Uid + '#' + cardId + '#' + activetype,
        storeappid: app.globalData.storeAppId,
        type: "coupon"
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              qrCode: 'https://static.711688.net.cn/upload/couponcode/' + res.data.Data
            })
          }
        }
        that.freshCode(cid, res.data.ServerTime);
      },
    })
  },
  // 刷新小程序码状态
  freshCode: function (cid, lastTime) {
    let that = this;
    var timesRun = 0;
    var timer = setInterval(function () {
      timesRun += 1;
      if (timesRun === 30) {
        clearInterval(timer);
      }
      wx.request({
        url: app.globalData.host + '/api/Coupon/IsCheckCard',
        data: {
          cid: cid,
          lastTime: lastTime
        },
        month: 'POST',
        success: function (res) {
          if (res.data.Code == 0) {
            if (res.data.Data != null) {
              let checkResult = res.data.Data;
              checkResult.oldExpireTime = utils.formatTime(utils.jianDate(checkResult.ExpireTime, checkResult.Amount));
              checkResult.oldExpireTime = checkResult.oldExpireTime.substr(0, 10).replace(/\//g, "-");
              that.setData({
                checkResult: checkResult
              })
              clearInterval(timer);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false,
            })
          }
        }
      })
    }, 3000)
    that.data.timer = timer;
  },
  // 加载更多
  loadMore: function () {
    var that = this;
    let tagindex = that.data.tagindex;
    if (that.data.loadingMore > 1 && that.data.CurrentPage < that.data.loadingMore) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      if (tagindex == 1) {
        that.getAiCardList();
      }
      if (tagindex == 2) {
        that.getCardItems();
      }
      if (tagindex == 3) {
        that.getAllCoupon();
      }
    } else {
      return
    }
  },
  //监听用户滑动页面事件
  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop);
    if (this.data.tagindex > 1) {
      this.setData({
        top: top
      })
    }
  }
})